package com.googlecode.ssdutils.jlauncher;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import com.googlecode.ssdutils.jlauncher.annotations.Launcher;

public class JLauncher {

	/**
	 * 
	 */
	private static final String COMMAND_LABEL = "command";
	private static final String HELP_LABEL = "help";
	OptionsFactory optionBuilder = new OptionsFactory();
	AnnotationsReader ar = new AnnotationsReader();

	/**
	 * @param args
	 * @throws ParseException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 */
	public static void main(String[] args) throws ParseException, IOException,
			ClassNotFoundException, InstantiationException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		new JLauncher().launch(args);
	}

	protected void launch(String[] args) throws ParseException, IOException,
			ClassNotFoundException, InstantiationException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		Options options = new Options();
		options.addOption(OptionBuilder.withArgName(COMMAND_LABEL).hasArg()
				.withDescription("command to be launched")
				.create(COMMAND_LABEL));
		options.addOption(OptionBuilder.withArgName(HELP_LABEL)
				.withDescription("print this help").create(HELP_LABEL));
		Set<LaunchConfiguration> launchConfigurations = ar
				.getLaunchConfiguration();
		LaunchConfiguration launchConfiguration = launchConfigurations
				.iterator().next();
		optionBuilder.buildOptions(options, launchConfiguration);
		CommandLineParser parser = new GnuParser();
		CommandLine line = parser.parse(options, args);
		if (!line.hasOption(HELP_LABEL)
				&& optionBuilder.initAndValidate(launchConfiguration, line)) {
			String cmd = Launcher.DEFAULT_COMMAND;
			if (line.hasOption(COMMAND_LABEL)) {
				cmd = line.getOptionValue(COMMAND_LABEL);
			}
			launchConfiguration.run(cmd);
		} else {
			printHelp(options);
		}
	}

	/**
	 * @param options
	 */
	protected void printHelp(Options options) {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("JLauncher", options);
	}

}
